<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use app\api\model\User;
use app\api\model\YaoqingRecords as Income;
use think\Db;
use think\Validate;
use app\service\Commission;
use think\Session;

class Invite extends Common {

    public function lists() {
        $way          = input('way/d', 1);
        $where['way'] = $way;
        $this->assign('way', $way);

        $search_type = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'number'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $this->assign('search', $search_type);

        $data = Db::name('user_invite_record')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();

        $users = Db::name('user')->where(['id'=>['in', array_merge(array_column($dataList, 'user_id'), array_column($dataList, 'touserid'))]])->column('*', 'id');
        $admins = Db::name('admin')->column('name', 'id');
        $state = ['改绑触发解绑', '解绑', '绑定'];
        foreach ($dataList as &$value) {
            $value['user_name'] = $users[$value['user_id']] ?? '';
            $value['touser_name'] = $users[$value['touserid']] ?? '';
            $value['admin_name'] = $admins[$value['admin_id']] ?? '';
            $value['state_text'] = $state[$value['state'] + 1];
        }

        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function unbind()
    {
        $id = input('id');
        return action('admin/member/inviteCode', ['id'=>$id, 'prev_id'=>0]);
    }
    public function unwelfare()
    {
        $id = input('id');

        $data = Db::name('user_invite_record')->find($id);

        $res = false;
        if ($data['reward_get'] == 0) {
            $res = db('user_invite_record')->where(['id'=>$id])->update(['reward_get'=>-1]);
        }
        return $res ? ['ret'=>'操作成功'] : ['err'=>'操作失败'];
    }

    public function welfare() {
        $where = ['user_id'=>['>', 0]];

        $search_type = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'number'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $this->assign('search', $search_type);

        $data = Db::name('user_invite_record')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();

        $users = Db::name('user')->where(['id'=>['in', array_merge(array_column($dataList, 'user_id'), array_column($dataList, 'touserid'))]])->column('*', 'id');
        $admins = Db::name('admin')->column('name', 'id');
        $state = ['改绑触发解绑', '解绑', '绑定'];
        foreach ($dataList as &$value) {
            $value['user'] = $users[$value['user_id']] ?? false;
            $value['touser_name'] = $users[$value['touserid']] ?? '';
            $value['admin_name'] = $admins[$value['admin_id']] ?? '';
            $value['state_text'] = $state[$value['state'] + 1];
        }

        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);

        return $this->fetch();
    }


    public function bind_after($userid = 0, $touserid = 0)
    {
        if (request()->isAjax()) {
            //$result = Commission::afterBind($userid, $touserid);
            $result = Commission::afterBind_new($userid, $touserid);
            return is_array($result) ? ['ret'=>$result] : ['err'=>$result];
        }else{
            return $this->fetch();
        }
    }

    public function bind($userid = 0, $touserid = 0)
    {
        $result = Commission::afterBind($userid, $touserid);
        $user = Db::name('user')->find($userid);
        $head = $user['name'] . '('.$user['id'].') ';
        $state1 = 0;
        $state2 = 0;
        $time = time();
        $exists = Db::name('yaoqing_records_reissue')->where(['touid'=>$userid, 'state'=>1])->select();
        if (count($exists)) {
            try {
                Db::startTrans();
                foreach ($exists as $key => $value) {
                    $state = Income::index($value['uid'], 0, $value['money'], $head . '绑定解除', 1, '', 1);
                    if (!$state) {
                        throw new \Exception($value['uid'] . "积分不足抵扣", 1);
                    }
                    Db::name('yaoqing_records_reissue')->where(['id'=>$value['id']])->update(['state'=>2]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return ['ret'=>$e->getMessage()];
            }
        }

        if (is_array($result)) {
            if ($result['commission_chongzhi']) {
                $content = $head . '绑定计算：金币充值奖励补发';
                $res = User::reward($userid, $result['chongzhi'], $content, 'topup');
                $state1 = 1;
                
                foreach ($res as $key => $value) {
                    Db::name('yaoqing_records_reissue')->insert([
                        'uid'=>$value['user_id'],
                        'touid'=>$user['id'],
                        'content'=>$content,
                        'money'=>$value['money'],
                        'time'=>$time,
                        'state'=>1
                    ]);
                    
                }
            }
            if ($result['commission_huiyuan']) {
                $money_rate = db('config_system')->where(['title'=>'money_rate'])->value('content');
                $content = $head . '绑定计算：金币充值奖励补发';
                $res = User::reward($userid, $result['huiyuan'] * $money_rate, $head . $content, 'topup');
                $state2 = 1;
                
                foreach ($res as $key => $value) {
                    Db::name('yaoqing_records_reissue')->insert([
                        'uid'=>$value['user_id'],
                        'touid'=>$user['id'],
                        'content'=>$content,
                        'money'=>$value['money'],
                        'time'=>$time,
                        'state'=>1
                    ]);
                }
            }
        }
        return $state1 || $state2 ? ['ret'=>'发放成功'] : ['ret'=>'发放失败'];
    }

    public function apply() {
        $state          = input('state/d', 0);
        $where['state'] = $state;
        $this->assign('state', $state);

        $search_type = input('param.search_typeid');
        $search_name = input('param.search_name');
        if ($search_name) {
            if (in_array($search_type, ['user_id', 'number'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $this->assign('search', $search_type);

        $data = Db::name('user_invite_apply')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();

        $users = Db::name('user')->where(['id'=>['in', array_merge(array_column($dataList, 'user_id'), array_column($dataList, 'touserid'))]])->column('*', 'id');
        $admins = Db::name('admin')->column('name', 'id');
        $state = ['改绑触发解绑', '解绑', '绑定'];
        foreach ($dataList as &$value) {
            $value['user_name'] = $users[$value['user_id']] ?? '';
            $value['touser_name'] = $users[$value['touserid']] ?? '';
            $value['admin_name'] = $admins[$value['shenhe_admin_id']] ?? '';
            $value['state_text'] = $state[$value['state'] + 1];
            $value['images'] = $value['images'] ? explode(',', $value['images']) : [];
        }

        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);

        return $this->fetch();
    }


    public function applyShenhe()
    {
        $id = input('id');
        $state = input('state');
        $data = Db::name('user_invite_apply')->master()->find($id);
        if (!$data) return ['err'=>'数据不存在'];
        if ($data['state']) return ['err'=>'数据已审核'];
        $res = db('user_invite_apply')->where(['id'=>$id])->update(['state'=>$state, 'shenhe_admin_id'=>$this->adminInfo['id'], 'shenhe_time'=>time()]);
        if ($res) {
            if ($state != 1) return ['ret'=>'操作成功'];
            return action('admin/member/inviteCode_new', ['id'=>$data['touserid'], 'prev_id'=>$data['user_id']]);
        }
        return ['err'=>'操作失败'];
    }
    public function superlists()
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $yquserid = $admin['name'];
        $search_type = input('param.search_typeid')?? 'user_id';
        $search_name = input('param.search_name')?? $yquserid;

        if ($search_name) {
            if (in_array($search_type, ['user_id', 'number'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        $this->assign('search', $search_type);

        // 查询并分页展示邀请记录
        $data = Db::name('user_invite_record')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $dataList = $data->all();

        // 获取用户姓名和管理员姓名
        $userIds = array_merge(array_column($dataList, 'user_id'), array_column($dataList, 'touserid'));
        $users = Db::name('user')->whereIn('id', $userIds)->column('name', 'id');
        $admins = Db::name('admin')->column('name', 'id');

        // 格式化数据列表
        foreach ($dataList as &$value) {
            $value['user_name'] = $users[$value['user_id']] ?? '';
            $value['touser_name'] = $users[$value['touserid']] ?? '';
            $value['admin_name'] = $admins[$value['admin_id']] ?? '';
        }

        // 计算统计信息（时间戳处理）
        $todayStart = strtotime(date('Y-m-d 00:00:00')); // 今日开始时间戳
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));   // 今日结束时间戳

        // 今日统计（使用whereTime方法处理时间戳）
        $todayStats = [
            'bind' => Db::name('user_invite_record')
                ->where('user_id',$yquserid)
                ->where('way', 1)
                ->whereBetween('create_time', [$todayStart, $todayEnd])
                ->count(),
            'cancel' => Db::name('user_invite_record')
                ->where('user_id',$yquserid)
                ->where('way', 0)
                ->whereBetween('create_time', [$todayStart, $todayEnd])
                ->count(),
            'unbind' => Db::name('user_invite_record')
                ->where('user_id',$yquserid)
                ->where('way', -1)
                ->whereBetween('create_time', [$todayStart, $todayEnd])
                ->count()
        ];

        // 总计统计
        $totalStats = [
            'bind' => Db::name('user_invite_record')->where('user_id',$yquserid)->where('way', 1)->count(),
            'cancel' => Db::name('user_invite_record')->where('user_id',$yquserid)->where('way', 0)->count(),
            'unbind' => Db::name('user_invite_record')->where('user_id',$yquserid)->where('way', -1)->count()
        ];

        // 生成统计话术
        $statsMsg = [
            'today' => "今日统计：正常绑定 {$todayStats['bind']} 条，取消绑定 {$todayStats['cancel']} 条，解绑 {$todayStats['unbind']} 条。",
            'total' => "总计统计：正常绑定 {$totalStats['bind']} 条，取消绑定 {$totalStats['cancel']} 条，解绑 {$totalStats['unbind']} 条。"
        ];

        // 传递数据到视图
        $page = $data->render();
        $this->assign('data', $dataList);
        $this->assign('page', $page);
        $this->assign('statsMsg', $statsMsg); // 传递统计话术

        return $this->fetch();
    }
    
    //推广信息相关
    /**
     * 团队管理页面 - 显示团队成员列表及统计数据
     *
     * @return mixed 渲染团队管理视图
     */
    public function teamListbak()
    {
        // 获取前端传递的时间范围参数（格式: 2025-05-23 01:00:00）
        $start = input('param.start');
        $end = input('param.end');

        // 保存原始参数到视图
        $this->assign('start', $start);
        $this->assign('end', $end);
        // 获取当前管理员绑定的用户ID
        $admin = Session::get('admin', 'mmjtAdmin');
             //dump($admin);
        if($admin['id']==1){//超管
            $userId = Input('param.userid');
            $this->assign('isadmin',1);
            $this->assign('userId',$userId);
        }else{
            $this->assign('isadmin',0);
            $userId = $admin['bind_uid'];
        }
        // 获取当前用户的邀请码
        $currentUser = Db::name('user')->where('id', $userId)->find();
        $inviteCode = $currentUser['yqm'];
        //echo $inviteCode;
        // 获取团队成员（不包含当前用户，按注册时间筛选）
        $teamMemberIds = array_unique($this->getTeamMembers($inviteCode, 1, $start, $end));
        //dump($teamMemberIds);
        // 1. 计算团队会员总数
        $memberCount = count($teamMemberIds);
        // 2. 计算指定时间范围内的总充值金额
        $totalRecharge = $this->calculateTeamRecharge($teamMemberIds,0,$start, $end);
        // 3. 计算指定时间范围内的vip类型总充值金额
        $totalVipRecharge = $this->calculateTeamRecharge($teamMemberIds,6,$start, $end);
        // 4. 计算今日新增会员（固定为今天0点到23:59:59）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d 23:59:59');
        if (empty($teamMemberIds)) {
            $todayNewMembers = 0;
        } else {
            $todayNewMembers = Db::name('user')
                ->where('id', 'in', $teamMemberIds)
                ->where('register_datetime', 'between', [$todayStart, $todayEnd])
                ->count();
        }
        //echo $todayNewMembers.'123';
        // 传递统计结果到视图
        $this->assign('memberCount', $memberCount);
        $this->assign('totalRecharge', $totalRecharge);
        $this->assign('totalVipRecharge', $totalVipRecharge);
        $this->assign('todayNewMembers', $todayNewMembers);
        //dump($teamMemberIds);
        // 获取团队成员详细信息（带分页）
//        $pageSize = 20;
//        $teamMembers = Db::name('user')
//            ->where('id', 'in', $teamMemberIds)
//            ->paginate($pageSize);
//        $this->assign('teamMembers', $teamMembers);
        return $this->fetch();
    }
    /**
     * 团队管理页面 - 显示团队成员列表及统计数据
     *
     * @return mixed 渲染团队管理视图
     */
     public function teamList()
    {
        //今日时间
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d 23:59:59');
        //昨日时间
        $yesdayStart=date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesdayEnd=date('Y-m-d 23:59:59', strtotime('-1 day'));
        //echo $yesdayStart;die;
        // 获取前端传递的时间范围参数（格式: 2025-05-23 01:00:00）
        $start = input('param.start');
        $end = input('param.end');

        // 保存原始参数到视图
        $this->assign('start', $start);
        $this->assign('end', $end);
        // 获取当前管理员绑定的用户ID
        $admin = Session::get('admin', 'mmjtAdmin');
        //dump($admin);
        if($admin['id']==1){//超管
            $userId = Input('param.userid');
            $this->assign('isadmin',1);
            $this->assign('userId',$userId);
        }else{
            $this->assign('isadmin',0);
            $userId = $admin['bind_uid'];
        }
        // 获取当前用户的邀请码
        $currentUser = Db::name('user')->where('id', $userId)->find();
        $inviteCode = $currentUser['yqm'];
        //echo $inviteCode;
        // 获取团队成员（包含当前用户,按注册时间筛选）
        $teamMemberIds = array_unique($this->getTeamMembers($inviteCode, 1, $start, $end));
        //dump($teamMemberIds);
        // 1. 计算团队会员总数
        $memberCount = count($teamMemberIds);

        //不限制时间 查总会员数 用此数查询后续筛选
        $teamMemberIdsall=array_unique($this->getTeamMembers($inviteCode, 1, '',''));
        // 2. 计算指定时间范围内的总充值金额
        $totalRecharge = $this->calculateTeamRecharge($teamMemberIdsall,0,$start, $end);
        $todayRecharge=$this->calculateTeamRecharge($teamMemberIdsall,0,$todayStart, $todayEnd);
        //echo $todayRecharge;
        $yesdayRecharge=$this->calculateTeamRecharge($teamMemberIdsall,0,$yesdayStart, $yesdayEnd);

        // 3. 计算指定时间范围内的vip类型总充值金额
        $totalVipRecharge = $this->calculateVipRecharge($teamMemberIdsall,6,$start, $end);
        $todayVipRecharge = $this->calculateVipRecharge($teamMemberIdsall,6,$todayStart, $todayEnd);
        $yesdayVipRecharge = $this->calculateVipRecharge($teamMemberIdsall,6,$yesdayStart, $yesdayEnd);

        // 4. 计算今日新增会员（固定为今天0点到23:59:59）
        if (empty($teamMemberIdsall)) {
            $todayNewMembers = 0;
            $yesdayNewMembers=0;
        } else {
            $todayNewMembers = Db::name('user')
                ->where('id', 'in', $teamMemberIdsall)
                ->where('register_datetime', 'between', [$todayStart, $todayEnd])
                ->field('id')
                ->count();
            $yesdayNewMembers= Db::name('user')
                ->where('id', 'in', $teamMemberIdsall)
                ->where('register_datetime', 'between', [$yesdayStart, $yesdayEnd])
                ->field('id')
                //->buildSql();构建sql
                ->count();
        }
        //echo $yesdayNewMembers;die;
        //dump($todayNewMembers);die;
        // 传递统计结果到视图
        $this->assign('memberCount', $memberCount);
        $this->assign('totalRecharge', $totalRecharge);
        $this->assign('totalVipRecharge', $totalVipRecharge);

        //今日相关
        $this->assign('todayNewMembers', $todayNewMembers);
        $this->assign('todayRecharge', $todayRecharge);
        $this->assign('todayVipRecharge', $todayVipRecharge);

        //昨日相关
        $this->assign('yesdayNewMembers', $yesdayNewMembers);
        $this->assign('yesdayRecharge', $yesdayRecharge);
        $this->assign('yesdayVipRecharge', $yesdayVipRecharge);

        //dump($teamMemberIdsall);
        // 获取团队成员详细信息（带分页）
//        $pageSize = 20;
//        $teamMembers = Db::name('user')
//            ->where('id', 'in', $teamMemberIdsall)
//            ->paginate($pageSize);
//        $this->assign('teamMembers', $teamMembers);
        $currentUid=$userId;
        $this->assign('currentuid',$currentUid);
        if($admin['id']==1) {//超管
            $superdai=Db::name('admin')
                ->alias('t1')
                ->join('user t2', 't1.bind_uid=t2.id')
                ->where(['t1.type'=>6])
                ->field('t1.id,t1.bind_uid,t2.name as sdname')
                ->order('id asc')
                ->select();
            $this->assign('superdai',$superdai);
            return $this->fetch('team_lista');
        }else{
            return $this->fetch();
        }
    }
    /**
     * 获取团队成员列表（先递归查询所有下级，再按时间筛选）
     *
     * @param string $inviteCode 邀请码
     * @param int $includeSelf 是否包含当前用户(1=包含,0=不包含,默认0)
     * @param string $startTime 开始时间(格式: Y-m-d H:i:s)
     * @param string $endTime 结束时间(格式: Y-m-d H:i:s)
     * @return array 团队成员ID列表
     */
    private function getTeamMembers($inviteCode, $includeSelf = 0, $startTime = '', $endTime = '')
    {
        $teamMembers = [];
        // 获取当前用户信息
        $currentUser = Db::name('user')->where('yqm', $inviteCode)->find();
        // 无论时间条件如何，直接包含当前用户（如果需要）
        if ($includeSelf) {
            $teamMembers[] = $currentUser['id'];
        }
        // 递归获取所有下级成员（不考虑时间条件）
        $this->getSubMembersRecursive($inviteCode, $teamMembers);
        // 如果没有时间筛选，直接返回所有成员
        if (empty($startTime) && empty($endTime)) {
            return $teamMembers;
        }
        // 按时间条件筛选成员
        return $this->filterMembersByTime($teamMembers, $startTime, $endTime);
    }
    /**
     * 递归获取下级成员（不考虑时间条件）
     */
    private function getSubMembersRecursive($inviteCode, &$teamMembers)
    {
        // 查询直接下级（不添加时间条件）
        $subMembers = Db::name('user')
            ->where('yqr', $inviteCode)
            ->column('id, yqm');
        foreach ($subMembers as $memberId => $yqm) {
            $teamMembers[] = $memberId;
            // 递归查询下级的下级
            $this->getSubMembersRecursive($yqm, $teamMembers);
        }
    }
    /**
     * 按时间条件筛选成员
     */
    private function filterMembersByTime($memberIds, $startTime, $endTime)
    {
        if (empty($memberIds)) {
            return [];
        }
        // 构建时间条件
        $query = Db::name('user')->where('id', 'in', $memberIds);
        if (!empty($startTime)) {
            $query->where('register_datetime', '>=', $startTime);
        }
        if (!empty($endTime)) {
            $query->where('register_datetime', '<=', $endTime);
        }
        // 返回筛选后的成员ID
        return $query->column('id');
    }
    /**
     * 计算团队在指定时间段内的有效充值金额
     *
     * @param array $teamMemberIds 团队成员ID列表
     * @param string $sid 套餐 1红包 2连麦 4礼物 5座驾 6vip
     * @param string $startTime 开始时间(格式: Y-m-d H:i:s)
     * @param string $endTime 结束时间(格式: Y-m-d H:i:s)
     * @return float 充值总金额
     */
    private function calculateTeamRecharge($teamMemberIds, $sid = 0, $startTime = '', $endTime = '')
    {
        if (empty($teamMemberIds)) {
            return 0;
        }
        // 构建基础查询
        $query = Db::name('topup')
            ->where('fk_userid', 'in', $teamMemberIds)
            ->where('state', 1); // 状态1=已支付
        // 添加sid条件（如果有）
        if ($sid) {
            $query->where('sid', $sid);
        }
        // 直接使用where条件组合（简化版）
        if (!empty($startTime)) {
            $query->where('addtime', '>=', $startTime);
        }
        if (!empty($endTime)) {
            $query->where('addtime', '<=', $endTime);
        }
        // 执行查询并返回总金额
        return $query->sum('price');
    }
    
        //计算VIP充值
    private function calculateVipRecharge($teamMemberIds, $sid = 0, $startTime = '', $endTime = '')
    {
        if (empty($teamMemberIds)) {
            return 0;
        }
        // 构建基础查询
        $query = Db::name('order_common')
            ->where('user_id', 'in', $teamMemberIds)
            ->where('status', 1); // 状态1=已支付
        // 添加sid条件（如果有）
        if ($sid) {
            $query->where('types', $sid);
        }
        // 直接使用where条件组合（简化版）
        if (!empty($startTime)) {
            $startTime=strtotime($startTime);
            $query->where('create_time', '>=', $startTime);
        }
        if (!empty($endTime)) {
            $endTime=strtotime($endTime);
            $query->where('create_time', '<=', $endTime);
        }
        //echo $query->buildSql();
        // 执行查询并返回总金额
        return $query->sum('money');
    }

}